<template>
  <div>
    <el-button type="primary" @click="addRole">新增角色</el-button>
    <el-table :data="list">
      <el-table-column prop="id" label="#" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button @click="editRole(scope.row)">编辑</el-button>
          <el-button @click="deleteRole(scope.row.id)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination v-model:current-page="page" v-model:page-size="size" :page-sizes="[10, 20, 50, 100]"
      :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="getList"
      @current-change="getList" />

    <my-dialog :title="dialogTitle" ref="dialogRef" @confirm="submitForm">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <el-form-item label="ID" v-if="editId">
          <el-input v-model="editId" disabled />
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
      </el-form>
    </my-dialog>
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted, reactive} from 'vue';
import {getRoleListApi, createRoleApi, updateRoleApi, deleteRoleApi} from '@/api/role';
import type {RoleCreateDto, RoleSingleDto} from '@/dtos/role.dto';
import MyDialog from '@/components/dialog/my-dialog.vue';

const list = ref<RoleSingleDto[]>([]);
const total = ref(0);
const page = ref(1);
const size = ref(10);

const editId = ref<string>("");
const dialogRef = ref<InstanceType<typeof MyDialog>>();
const dialogTitle = ref<string>("编辑角色");
const ruleFormRef = ref();
const ruleForm = reactive<RoleCreateDto>({
  name: '',
  createdBy: '',
  createdAt: new Date(),
});

const rules = reactive({
  name: [{required: true, message: '请输入角色名称', trigger: 'blur'}],
});

const getList = async () => {
  const res = await getRoleListApi({page: page.value, size: size.value});
  list.value = res.list;
  total.value = res.total;
};

const submitForm = async () => {
  await ruleFormRef.value?.validate(async (valid: any) => {
    if (valid)
    {
      if (editId.value)
      {
        await updateRoleApi(editId.value, ruleForm);
      } else
      {
        await createRoleApi(ruleForm);
      }
      getList();
      dialogRef.value?.closeDialog();
    }
  });
};

const addRole = () => {
  editId.value = '';
  dialogRef.value?.openDialog();
};

const editRole = (row: RoleSingleDto) => {
  editId.value = row.id;
  Object.assign(ruleForm, row);
  dialogRef.value?.openDialog();
};

const deleteRole = async (id: string) => {
  await deleteRoleApi(id);
  getList();
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped></style>